package ocbn.remotelab.GUI;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import ocbn.remotelab.client.*;
import ocbn.remotelab.client.EventListener;
import ocbn.remotelab.events.*;
/**
 * Main Selection screen that lets the user to choose which action to perform: <br>
 *   Launch MassSpec Event viewer <br>
 *   Launch OCBN Lab Management viewer(not implemented) <br>
 * <br>
 * A connection to the server is automatically started when the application is
 * launched. <br>
 * <br>
 * User can exit the app by choosing the Exit option in the menu. <br>
 * User can hide the app by choosing the hide option in the menu or press the
 * escape key on the blackberry. <br>
 * User can connect/disconnect from the server from the menu. <br>
 * @author c9wuke
 */
public class SelectionScreen extends MainScreen implements EventListener{

    //declare Layout Managers for selection portion
    private VerticalFieldManager fieldManagerLeft;
    private HorizontalFieldManager fieldManagerBack;
    private VerticalFieldManager fieldManagerRight;

    //for the Log portion.
    VerticalFieldManager vfmlog;
    LabelField logTitle;
    LabelField connLogs;
    LabelField lastEventLogs;

    //Declare PacketProcessor and Eventhandler.
    private PacketProcessor pp;
    private EventHandler eh;

    private Event connectionEvent;

    /**
     * Creates a selection screen for the RemoteLab application.
     */
    public SelectionScreen() {
        super(Screen.DEFAULT_CLOSE);

        /**
         * Start a connection automaticaly when the application starts.
         */      
        pp = new PacketProcessor(
                "Socket://127.0.0.1:7777", "Tester", "RandomTester");
        eh = new EventHandler();
        pp.addListener(eh);
        pp.connect();

      
        pp.addListener(this);

        //Create a title of the selectionScreen.
        LabelField title = new LabelField("OCBN Remote Lab",
                LabelField.USE_ALL_WIDTH);
        setTitle(title);

        buildSelectionButtons();

       //Add a seperator field.
        add(new SeparatorField()); 
     
        buildLogWindow();
    }

    /**
     * Builds a log window that shows sever activities as well as the most <br>
     * recent event.
     */
    void buildLogWindow(){
     //   vfmlog = new VerticalFieldManager(
       //         Manager.VERTICAL_SCROLL);
        logTitle = new LabelField("Connection Status:",
        LabelField.USE_ALL_WIDTH);
        add(logTitle);
        connLogs  = new LabelField("", LabelField.USE_ALL_WIDTH);
        connLogs.setFont(Font.getDefault().derive(Font.PLAIN, 12));
        lastEventLogs = new LabelField("No recent event.", LabelField.USE_ALL_WIDTH);
        lastEventLogs.setFont(Font.getDefault().derive(Font.PLAIN, 12));
        add(connLogs);
        add(new LabelField("Most Recent Event:", LabelField.USE_ALL_WIDTH));
        add(lastEventLogs);
    }

    /**
     * Called when PacketProcessor encounters a server related event.
     * @param e The incoming event object.
     */
    public void EventReceived(Event e){

        connectionEvent = e;
        if (e instanceof ConnStateEvent){
        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
               connLogs.setText(connectionEvent.getDetails()+"\n");
            }
        });
        } else if (e instanceof MassSpectrometerStateEvent){
            lastEventLogs.setText(e.toString());
        }
    }
    
    /**
     * Creates 2 buttons: MS event viewer and LIMS viewer
     * Add listeners for the MS eventlog button.
     */
    void buildSelectionButtons(){
         //manager for the buttons: lay them out horizontally
        fieldManagerLeft = new VerticalFieldManager();
        fieldManagerRight = new VerticalFieldManager();
        fieldManagerBack = new HorizontalFieldManager(
                Manager.HORIZONTAL_SCROLL);

        add(fieldManagerBack);

        fieldManagerBack.add(fieldManagerLeft);
        fieldManagerBack.add(fieldManagerRight);

        //An Image for the MS event viewer button.
        Bitmap MSImage = Bitmap.getBitmapResource("massspec.jpg");
        BitmapField bitmap = new BitmapField();
        bitmap.setBitmap(MSImage);

        //An image for OCBN lab management button.
        Bitmap ocbnImage = Bitmap.getBitmapResource("ocbn.gif");
        BitmapField bitmap2 = new BitmapField();
        bitmap2.setBitmap(ocbnImage);

        //Create Button so the user can view speicfic pass events.
        ButtonField massSpec = new ButtonField("MS Event log",
                ButtonField.CONSUME_CLICK );
        ButtonField lms = new ButtonField("Lab Event Log",
                ButtonField.CONSUME_CLICK );

        //adds the images and buttons to the fieldManager.
        fieldManagerLeft.add(bitmap);
        fieldManagerLeft.add(massSpec);
        fieldManagerRight.add(bitmap2);
        fieldManagerRight.add(lms);

        //Create a listener for the MS Event button.
        massSpec.setChangeListener(new FieldChangeListener() {

            public void fieldChanged(Field field, int context) {

                //Launch the Table GUI if clicked.
                MSTableScreen ms = new MSTableScreen();
                pp.addListener(ms);
                UiApplication.getUiApplication().pushScreen(ms);

            }
        });
    }

    /**
     * Define application close behaviour, hides the screen to the background
     * when the user closes the app by pressing the "escape" button
     * on the device.
     */
    public void close() {
        UiApplication.getUiApplication().requestBackground();
    }

    /**
     * Make a menu and define menu item properties.
     * @param menu the menu object
     * @param instance the instance associated with the menu object.
     */
    protected void makeMenu(Menu menu, int instance) {
        menu.add(hide);
        if (pp.isRunning()) {
            menu.add(closeCon);
        } else {
            menu.add(openCon);
        }
        menu.add(exit);
    }
    //Closes the connection.
    private MenuItem closeCon = new MenuItem("Close Connection", 110, 10) {

        public void run() {
            pp.terminate();
        }
    };
    //Exit the application copmletely.
    private MenuItem exit = new MenuItem("Exit", 110, 10) {

        public void run() {
            System.exit(0);
        }
    };

    //Hides the GUI by sending it to the background.
    private MenuItem hide = new MenuItem("Hide Application", 110, 10) {

        public void run() {

            UiApplication.getUiApplication().requestBackground();
        }
    };
    
    //Launch the packetProcessor/connection thread.
    private MenuItem openCon = new MenuItem("Connect to Server", 110, 10) {

        public void run() {

            pp.connect();

        }
    };

    /**
     * Overiding the parent method to avoid save Prompt().
     * @return always returns true
     */
    protected boolean onSavePrompt(){
        return true;
    }


}







